The calendar module defines the Calendar class, which encapsulates calculations for values such as the dates of the weeks in a given month or year. In addition, the TextCalendar and HTMLCalendar classes can produce pre-formatted output.
The prmouth() method is a simple function that produces the formatted text output for a month.
In [3]:
import calendar
c = calendar.TextCalendar(calendar.SUNDAY)
c.prmonth(2017, 7)
The example configures TextCalendar to start weeks on Sunday, following the American convention. The default is to use the European convention of starting a week on Monday.
A similar HTML table can be produced with HTMLCalendar and formatmonth(). The rendered output looks roughly the same as the plain text version, but is wrapped with HTML tags. Each table cell has a class attribute corresponding to the day of the week, so the HTML can be styled through CSS.
To produce output in a format other than one of the available defaults, use calendar to calculate the dates and organize the values into week and month ranges, then iterate over the result. The weekheader(), monthcalendar(), and yeardays2calendar() methods of Calendar are especially useful for that.
Calling yeardays2calendar() produces a sequence of “month row” lists. Each list includes the months as another list of weeks. The weeks are lists of tuples made up of day number (1-31) and weekday number (0-6). Days that fall outside of the month have a day number of 0.
In [4]:
import calendar
import pprint
cal = calendar.Calendar(calendar.SUNDAY)
cal_data = cal.yeardays2calendar(2017, 3)
print('len(cal_data) :', len(cal_data))
top_months = cal_data[0]
print('len(top_months) :', len(top_months))
first_month = top_months[0]
print('len(first_month) :', len(first_month))
print('first_month:')
pprint.pprint(first_month, width=65)
In [ ]: